<template>
  <scroll-view scroll-y="true" :scroll-top="scrollTop" :show-scrollbar="false" class="contactsLayout"
    :scroll-with-animation="true" :scroll-into-view="toView">
    <view class="gongNengQuYu">
      <view class="gongNengQuYu-search scroll_item" @click="To('search')">
        <image class="scroll_item_img" src="/src/static/svg/jia.svg" mode="widthFix" />
        <view class="scroll_item_name">搜索</view>
      </view>
      <view class="gongNengQuYu-xpy scroll_item" @click="To('xpy')">
        <image class="scroll_item_img" src="/src/static/svg/xinpengyou.svg" mode="widthFix" />
        <view class="scroll_item_name">新朋友</view>
        <view class="scroll_item_num" v-if="unReadNum != 0">{{ unReadNum }}</view>
      </view>
    </view>
    <view class="center">
      <view @click="toUserPage(item)" :class="['scroll_item', item.type]" v-for="(item, index) in friendList"
        :key="index" :id="item?.value" :ref="item.name">
        <image v-if="item.type == 'person'" class="scroll_item_img" :src="item.friendImg" mode="widthFix" />
        <view v-if="item.type == 'person'" class="scroll_item_name">{{ item.friendNickname }}</view>
        {{ item.type == 'person' ? '' : item.value == "#" ? '#' : item.value.toLocaleUpperCase() }}
      </view>
    </view>
    <view class="total">{{ friendNum > 0 ? `${friendNum}个朋友` : '没有好友,去加好友吧' }}</view>
  </scroll-view>
  <view class="sideNav">
    <view class="letter" v-for="(item) in letter" @click="goToView(item)">{{ item }}</view>
  </view>
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app';
import { nextTick, reactive, ref, computed } from 'vue';
import { getFriendList, getNumForMakeFriend } from "../../api/contacts"
import { useUserStore } from "../../store/modules/user"
import '../../static/pinyin4js';
import { FG } from "../../api/req.js"

let userStore = useUserStore()
let imgUrl = `${FG.baseUrl}/static/`
let letter = ["^", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "#"]
let toView = ref("")
let scrollTop = ref(0)
let friendList = reactive([])
let friendNum = computed(() => {
  let num = 0
  friendList.forEach(item => {
    if (item.type == 'person') num++
  })
  return num
})

let unReadNum = ref(0)
function goToView(letter) {
  if (letter != "^" && letter != "#") {
    toView.value = letter
    nextTick(() => {
      toView.value = ""
    })
  }
  else if (letter == '#') {
    toView.value = "end"
    nextTick(() => {
      toView.value = ""
    })
  } else if (letter == "^") {
    scrollTop.value = 0
    nextTick(() => {
      scrollTop.value = 0.01
    })
  }
}


function To(target) {
  switch (target) {
    case "search":
      uni.navigateTo({ url: '/pages/search/search' })
      break
    case "xpy":
      uni.navigateTo({ url: '/pages/friendRequest/friendRequest' })
      break
    case "qunliao":
      break
  }
}

onLoad(async () => {
  uni.setNavigationBarTitle({
    title: '联系人'
  })
  let user = uni.getStorageSync('user')
  if (user) {
    userStore.user = user
  } else {
    uni.navigateTo({ url: '/pages/login/login' })
  }

})
onShow(async () => {
  try {
    let userListNoRef = []
    function setPy() {
      for (let i = 0; i < userListNoRef.length; i++) {
        let py = []
        function isChineseChar(str) {
          return /[\u4e00-\u9fa5\u0041-\u005a\u0061-\u007a]+/.test(str);
        }
        for (let j = 0; j < userListNoRef[i].friendNickname.length; j++) {
          if (isChineseChar(userListNoRef[i].friendNickname[i]) && py.length < 4) {
            py.push(PinyinHelper.getShortPinyin(userListNoRef[i].friendNickname[j]))
          }
        }
        if (py.length < 4 && py.length > 0) {
          for (let i = py.length; i < 4; i++) {
            py.push("z")
          }
        }
        if (py.length == 0) {
          for (let i = 0; i < 4; i++) {
            py.push("#")
          }
        }
        py = py.join("")
        userListNoRef[i].py = py
        userListNoRef[i].type = "person"
      }
    }
    let res = await getFriendList({ uid: userStore.user._id })
    if (res.status == 200) {
      userListNoRef.splice(0, userListNoRef.length)
      res.data.forEach(item => {
        userListNoRef.push(item)
      });
    }
    setPy()
    userListNoRef.sort((a, b) => {
      if (a.py !== "####" && b.py === "####") return -1;
      if (a.py === "####" && b.py !== "####") return 1;
      if (a.py === "####" && b.py === "####") return 0;
      return a.py.localeCompare(b.py);
    });
    let arr_user = []
    let letter = ""
    for (let i = 0; i < userListNoRef.length; i++) {
      if (userListNoRef[i].py[0] != letter) {
        letter = userListNoRef[i].py[0]
        arr_user.push({ type: "letter", value: userListNoRef[i].py[0] })
        arr_user.push(userListNoRef[i])
      } else {
        arr_user.push(userListNoRef[i])
      }
    }
    friendList.splice(0, friendList.length)
    for (let i = 0; i < arr_user.length; i++) {
      if (arr_user[i].type == "person") {
        arr_user[i].friendImg = `${imgUrl}${arr_user[i].friendImg}`
      }
      friendList.push(arr_user[i])
    }
    let { num } = await getNumForMakeFriend({ isclear: false, uid: userStore.user._id })
    unReadNum.value = num
  }
  catch (err) {
    console.log(err);
  }
})
function toUserPage(item) {
  // console.log(item);
  if (item.type == "letter") return
  uni.navigateTo({ url: `/pages/user/user?userId=${item.friendID}&friendStatus=200&remark=${item.friendNickname}` })
}

</script>



<style lang="scss" scoped>
.contactsLayout {
  width: 100%;
  height: calc(100vh - 44px - env(safe-area-inset-top) - var(--tab-bar-height) - env(safe-area-inset-bottom));
  position: relative;
  overflow: hidden;

  .scroll_item {
    width: 100%;
    height: 100rpx;
    display: flex;
    align-items: center;
    padding: 0 20rpx;
    border-bottom: 1px solid #cccccc5a;
    position: relative;

    .scroll_item_img {
      width: 80rpx;
      height: 80%;
      margin-right: 20rpx;
    }

    .scroll_item_name {
      max-width: 80%;
      text-wrap: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }

    .scroll_item_num {
      width: 40rpx;
      height: 40rpx;
      background-color: red;
      border-radius: 50%;
      text-align: center;
      line-height: 40rpx;
      color: #fff;
      position: absolute;
      top: 30%;
      right: 10%;
    }
  }

  .scroll_item:active {
    background-color: #eee;
  }

  .scroll_item.letter {
    display: block;
    width: 100%;
    height: 30rpx;
    background-color: #eee;
    font-size: 26rpx;
    text-align: center;
    line-height: 30rpx;
  }

  .total {
    width: 100%;
    height: 80rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.sideNav {
  width: 30rpx;
  position: fixed;
  top: calc(50rpx + 44px);
  right: 10rpx;

  .letter {
    font-size: 26rpx;
    text-align: center;
    color: #888;
    margin-bottom: 2rpx;
  }
}
</style>